package algorithmic_data_structure.链表;


/**
 * 删除链表中的指定值
 */
public class DeleteValue {
    public static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    public static void main(String[] args) {
        ListNode node1 = new ListNode(1);
        ListNode node2 = new ListNode(2);
        node1.next = node2;
        ListNode node3 = new ListNode(3);
        node2.next = node3;
        ListNode node4 = new ListNode(3);
        node3.next = node4;
        ListNode node5 = new ListNode(5);
        node4.next = node5;

        ListNode node = deleteValue(node1, 5);

        while (node != null) {
            System.out.println(node.val);
            node = node.next;
        }
    }

    public static ListNode deleteValue(ListNode head, int value) {
        while (head != null && head.val == value) {
            head = head.next;
        }
        //这里不能cur = head.next 因为上面之后head有可能为null
        ListNode cur = head;
        ListNode pre = head;

        while (cur != null) {
            if (cur.val == value) {
                pre.next = cur.next;
            } else {
                pre = cur;
            }
            cur = cur.next;
        }

        return head;
    }
}

